
public class InterruptExample {

    public static void main(String[] args) {
        Thread myThread = new Thread(new MyRunnable());
        myThread.start(); // 启动线程

        // 主线程等待一段时间后中断myThread
        try {
            Thread.sleep(2000); // 等待2秒钟
            myThread.interrupt(); // 发送中断信号
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    static class MyRunnable implements Runnable {
        @Override
        public void run() {
            while (!Thread.currentThread().isInterrupted()) {
                System.out.println("线程正在执行...");
                try {
                    Thread.sleep(1000); // 线程每隔1秒钟执行一次
                } catch (InterruptedException e) {
                    // 捕获到中断信号后，线程会退出循环
                    System.out.println("线程被中断，即将退出...");
                    Thread.currentThread().interrupt(); // 重新设置中断状态
                }
            }
        }
    }
}